//
//  ProjectChooseViewController.m
//  EducationAdminClient
//
//  Created by kwsdzjx on 16/5/13.
//  Copyright © 2016年 周佳兴. All rights reserved.
//选项卡

#import "ProjectChooseViewController.h"
#import "ProjectModel.h"
#import "LoginViewController.h"
#import "ProjectCellTableViewCell.h"
#import "ProjectCollectionViewCell.h"
#import "CustomFlowLayout.h"


#import "NewPagedFlowView.h"
#import "PGIndexBannerSubiew.h"


#define Width [UIScreen mainScreen].bounds.size.width

#define Height (578+194)/2

@interface ProjectChooseViewController ()<NewPagedFlowViewDelegate, NewPagedFlowViewDataSource>{
    NSMutableArray *dataArr;
    NewPagedFlowView *pageFlowView;
}

@property (strong, nonatomic)CustomFlowLayout *layout;
/**
 *  图片数组
 */
@property (nonatomic, strong) NSMutableArray *imageArray;

/**
 *  指示label
 */
@property (nonatomic, strong) UILabel *indicateLabel;

@end

@implementation ProjectChooseViewController


static const CGFloat MJDuration = 0.5;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    self.programaUrl = getBase();
    
    
    
    //*** dataSource arr
    dataArr = [[NSMutableArray alloc]init];
   

    self.imageArray = [[NSMutableArray alloc]init];

    
    UIImageView *logoImg =[[UIImageView alloc]init];
    
    logoImg.image = [UIImage imageNamed:@"name"];
    
    [self.view addSubview:logoImg];
    
    
    [logoImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view.mas_centerX);
        make.top.equalTo(self.view.mas_top).offset(230/2);
    }];

    //*** request the data
    [self dataRequest];
    

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}




#pragma mark NewPagedFlowView Delegate
- (CGSize)sizeForPageInFlowView:(NewPagedFlowView *)flowView {
    
    
    return CGSizeMake(Width - 84, Height);
}

#pragma mark NewPagedFlowView Datasource
- (NSInteger)numberOfPagesInFlowView:(NewPagedFlowView *)flowView {
    return dataArr.count;
}

- (UIView *)flowView:(NewPagedFlowView *)flowView cellForPageAtIndex:(NSInteger)index{
    PGIndexBannerSubiew *bannerView = (PGIndexBannerSubiew *)[flowView dequeueReusableCell];
    if (!bannerView) {
        bannerView = [[PGIndexBannerSubiew alloc] initWithFrame:CGRectMake(0, 0, Width - 84, Height)];
        bannerView.layer.cornerRadius = 8;
        bannerView.layer.masksToBounds = YES;
    }
    
    //    [bannerView.mainImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:hostUrlsImg,imageDict[@"img"]]] placeholderImage:[UIImage imageNamed:@""]];
    bannerView.mainImageView.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"pro_img%li", index%3]];
        ProjectModel *model = dataArr[index];

    bannerView.mainImageView.label.text = [NSString stringWithFormat:@"%@", model.programa_name];
    bannerView.allCoverButton.tag = index;
    [bannerView.allCoverButton addTarget:self action:@selector(didSelectBannerButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    
    return bannerView;
}

#pragma mark --点击轮播图
- (void)didSelectBannerButtonClick:(UIButton *) sender {
    
    NSInteger index = sender.tag;
    
    NSLog(@"点击了第%ld张图",(long)index + 1);
    
    // 动态改变 UI style
    NSString *proJectStyle = [NSString stringWithFormat:@"%ld", index%2];
    
    saveUIStyle(proJectStyle);
    ProjectModel *model = dataArr[index];
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setObject:model.proId forKey:PROID];
    [userDefault setObject:model.programa_url forKey:PROGRAMA];
    [userDefault setObject:model.pro_port forKey:PORT];
    [userDefault setObject:model.programa_name forKey:PROGRAMANAME];

    [userDefault synchronize];
    LoginViewController *loginVC = [[LoginViewController alloc]init];
    loginVC.projectArr = dataArr;
    [self presentViewController:loginVC animated:YES completion:^{
        
    }];
    
    if(index==dataArr.count-1){
        
        return;
    }
}

- (void)didScrollToPage:(NSInteger)pageNumber inFlowView:(NewPagedFlowView *)flowView {
    
    NSLog(@"滚动到了第%ld页",pageNumber);
}

- (NSMutableArray *)imageArray {
    if (_imageArray == nil) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

#pragma mark - createUI
-(void)createUI{
    self.view.backgroundColor = [UIColor whiteColor];

    
    if (pageFlowView!=nil) {
        [pageFlowView removeFromSuperview];
        pageFlowView = nil;
    }
    pageFlowView = [[NewPagedFlowView alloc] initWithFrame:CGRectMake(0, (230+122+60)/2, Width, Height + 24)];
    pageFlowView.backgroundColor = [UIColor clearColor];
    pageFlowView.delegate = self;
    pageFlowView.dataSource = self;
    pageFlowView.minimumPageAlpha = 0.4;
    pageFlowView.minimumPageScale = 0.8;
    
    [self.view addSubview:pageFlowView];

    //添加到主view上
    [self.view addSubview:self.indicateLabel];

}

#pragma mark - Refresh
-(void)loadNewData{
    [self.tbView.header beginRefreshing];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(MJDuration * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self dataRequest];
        
        // 拿到当前的下拉刷新控件，结束刷新状态
        [self.tbView.header endRefreshing];
    });
    
}

#pragma mark - DataRequest
-(void)dataRequest{
    
    NSMutableDictionary *parama = [[NSMutableDictionary alloc]init];
    [parama setObject:@"1" forKey:@"source"];
    
    [parama setObject: getSessionId() forKey:@"sessionId"];

    NSString *requestStr = [NSString stringWithFormat:@"%@%@", self.programaUrl, PROJECTREQUEST_URL];
    [NetRequest requestUrl:requestStr andParamas:parama andReturnBlock:^(NSData *data, NSError *error) {
        if (!error&&data!=nil) {
            id obj = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            NSLog(@"%@", string);
            
            if ([obj valueForKey: @"promptMessage"]) {
                [[NSNotificationCenter defaultCenter]postNotificationName:@"relogin" object:@"relogin"];
                
            }
            
            [self dataUes:obj];
            NSLog(@"%@", obj);
            
        }else{
            NSString *str = [NSString stringWithFormat:@"%@", error.localizedDescription];
            [self showLabelWithText:str];
            NSLog(@"%@", str);
        }
    }];
}

#pragma mark - data USE
-(void)dataUes:(id)obj{
    NSArray *arr = [[NSArray alloc]initWithArray:obj];
    
    [dataArr removeAllObjects];

    for (NSDictionary *dic in arr) {
        ProjectModel *model = [[ProjectModel alloc]init];
        model = [model initWithDictionary:dic error:nil];
        [dataArr addObject:model];
    }
    
    [self createUI];
    [self.collectionView reloadData];
}

- (void)viewDidLayoutSubviews {
    
    [super viewDidLayoutSubviews];
    
    self.layout.itemSize = CGSizeMake(620/2, 400/2);
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
